<?php
namespace app\common\model;

use think\Facade\Db;
use think\helper\Str;
use think\Model;
use think\model\concern\SoftDelete;

class User extends Model {
	use SoftDelete;
	protected $pk = 'user_id';
	protected $autoWriteTimestamp = true;
	protected $deleteTime = 'delete_time';
	public static function onBeforeInsert($user) {
		$user->create_ip = request()->ip();
		$user->create_time = time();
	}
	public static function onBeforeUpdate($user) {
		$user->update_ip = request()->ip();
		$user->update_time = time();
	}
	/**
	 * 注册用户
	 * @DateTime 2019-12-15
	 * @Author   BadmintonCode
	 * @param    string        $email    邮箱
	 * @param    string        $password 密码
	 * @param    integer       $status   状态
	 * @param    integer       $group_id 用户组
	 * @param    string        $addition 备注
	 * @return   [type]                  [description]
	 */
	public static function register($email, $password, $status = 0, $group_id = 0, $addition = '') {
		$email = trim($email);
		if (!$email) {
			return 'email.empty';
		}
		if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
			return 'email.format';
		}

		$password = trim($password);
		if (!$password) {
			return 'password.empty';
		}
		if (strlen($password) < 6) {
			return 'password.short';
		}
		if (self::whereEmail($email)->count() > 0) {
			return 'email.exist';
		}
		if ($status != 1 && $status != 0) {
			return 'status.error';
		}
		if (!Db::name('group')->where('group_id', $group_id)->count()) {
			return 'group.notExist';
		}
		$salt = Str::random($length = 16);
		$user = self::create([
			'email' => $email,
			'salt' => $salt,
			'password' => salt_password($salt, $password),
			'group_id' => $group_id,
			'status' => $status,
			'addition' => $addition,
		]);
		trace('管理员注册：' . $email, 'notice');
		return $user;
	}

	public static function password($user_id, $password) {
		if (!$user_id) {
			return 'user_id,empty';
		}
		$password = trim($password);
		if (!$password) {
			return 'password.empty';
		}
		if (strlen($password) < 6) {
			return 'password.short';
		}
		$user = self::whereUserId($user_id)->find();
		if (!$user) {
			return 'user.notExist';
		}
		$salt = Str::random($length = 16);
		$user->password = salt_password($salt, $password);
		$user->salt = $salt;
		$user->save();
		trace('管理员修改密码：' . $user_id, 'notice');
		return true;
	}

	public function getLoginTimeAttr($value) {
		if (!$value) {
			return;
		}

		return date('Y-m-d H:i:s', $value);
	}

}